package com.exposit.books.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;






import com.exposit.books.domain.Book;
import com.exposit.books.domain.Buyer;
import com.exposit.books.service.BookService;
import com.exposit.books.service.UserService;

@Controller
@RequestMapping("/book")
public class BookController {
	
	@Autowired
	private BookService bookService;
	
	@Autowired
	private UserService userService;
	
		
	@RequestMapping(value="/{bookID}", method= { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView showBook(@PathVariable("bookID") String bookId, HttpSession session, Model model) {
		if (session.getAttribute("user") == null)
		{
			ModelAndView mav = new ModelAndView();
			mav.setViewName("errorPage");
			return mav;
		}
		Book book = bookService.getBookById(Long.parseLong(bookId));
		
		ModelAndView mav = new ModelAndView("redirect:/book/"+book.getId());
		mav.addObject("book", book);
		mav.setViewName("book");
		return mav;
	}
	
	@RequestMapping(value = "/order", method = { RequestMethod.POST })
	public ModelAndView order(
		@RequestParam(value = "count", required = true) String count,
		@RequestParam(value = "address", required = true) String address,
		@RequestParam(value = "payment", required = true) String payment,
		@RequestParam(value = "bookID", required = true) String book,
		HttpServletRequest request, HttpSession session) {
		
		userService.newOrder((Buyer)session.getAttribute("user"), bookService.getBookById(Long.parseLong(book)), Long.parseLong(count), address, payment);
		
		ModelAndView model = new ModelAndView("redirect:/profile/"+((Buyer)session.getAttribute("user")).getId());
		return model;
	}
}
